package com.zgg.task;

import com.zgg.config.AliOssProperties;
import com.zgg.utils.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.Set;

/**
 * 定时删除临时文件
 */
@EnableScheduling
@Component
public class RemoveTempFileScheduled {
    private Logger logger = LoggerFactory.getLogger(RemoveTempFileScheduled.class);

    @Autowired
    private RedisUtils redisUtils;

    @Scheduled(cron = "0 0 0/1 * * * ")
    public void removeTempFile() {
        logger.error("==========>>>>>    删除临时文件定时任务开始执行......");
        long startTime = System.currentTimeMillis();
        Set<Object> set = redisUtils.smembers(AliOssProperties.downFileCache);
        if (set != null && set.size() > 0) {
            for (Object o : set) {
                String filePaths = String.valueOf(o);
                File file = new File(filePaths);
                if (file.exists()) {
                    if (!file.delete()) {
                        logger.error("==========>>>>>     临时文件【" + filePaths + "】删除失败！");
                    } else {
                        long num = redisUtils.srem(AliOssProperties.downFileCache, filePaths);
                    }
                }
            }
        }
        long endTime = System.currentTimeMillis();
        logger.error("==========>>>>>    删除临时文件定时任务执行结束,总共耗时：【" + (endTime - startTime) + "】");
    }

}
